package com.lycx.businessmanager.service.impl;

import java.util.Date;
import java.util.List;

import com.lycx.businessmanager.constant.ConstantsDbOperation;
import com.lycx.businessmanager.constant.ConstantsMessage;
import com.lycx.businessmanager.constant.ConstantsTableName;
import com.lycx.businessmanager.dao.UserDao;
import com.lycx.businessmanager.manager.SequenceManager;
import com.lycx.businessmanager.model.User;
import com.lycx.businessmanager.service.IUserService;
import com.lycx.businessmanager.util.MyUtils;
import com.lycx.businessmanager.util.SysContext;

public class UserServiceImpl implements IUserService {

	private UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> select(User user) {
		return (List<User>) userDao.select(ConstantsDbOperation.USER_SELECT, user);
	}

	@Override
	public String add(User user) {
		String result = null;
		try {
			List<User> list = selectRepeat(user);
			if (list != null && list.size() > 0) {
				result = ConstantsMessage.USER_REPEAT_FAIL;
			} else {
				user.setId(SequenceManager.createId(ConstantsTableName.USER));
				user.setCreateTime(new Date());
				user.setPassword(MyUtils.encryptMD5(SysContext.DEFAULT_PASSWORD));
				userDao.insert(ConstantsDbOperation.USER_INSERT, user);
				result = ConstantsMessage.USER_ADD_SUCCESS;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = ConstantsMessage.USER_ADD_FAIL;
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	private List<User> selectRepeat(User user) {
		return (List<User>) userDao.select(ConstantsDbOperation.USER_SELECT_REPEAT, user);
	}

	@Override
	public String del(int[] ids) {
		String result = null;
		try {
			if (ids != null && ids.length > 0) {
				for (int id : ids) {
					User user = new User();
					user.setId(id);
					userDao.delete(ConstantsDbOperation.USER_DELETE, user);
				}
				result = ConstantsMessage.USER_DEL_SUCCESS;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = ConstantsMessage.USER_DEL_FAIL;
		}
		return result;
	}


	@Override
	public String mod(User user) {
		String result = null;
		try{
			List<User> list = selectRepeat(user);
			if (list != null && list.size() > 0) {
				result = ConstantsMessage.USER_REPEAT_FAIL;
			} else {
		        userDao.update(ConstantsDbOperation.USER_UPDATE, user);
		        result = ConstantsMessage.USER_MOD_SUCCESS;
			}
		    
		}catch(Exception e){
			e.printStackTrace();
			result = ConstantsMessage.USER_MOD_FAIL;
		}
        return result;
	}
	
	
}
